package com.antdant.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lee Yunc
 * @Date 2021/2/24 17:14
 * @Description: 实现基本的跨域请求
 * @Version 1.0
 */
@Configuration
public class CorsConfig {
    /**
     * 支持跨域请求
     *
     * @return
     */
    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);//允许请求带有验证信息
        List<String> allowedOriginPatterns = new ArrayList<>();// 允许访问的客户端域名
        allowedOriginPatterns.add("*");//spring boot2.4版本不加这行配置会报错
        corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
        //corsConfiguration.addAllowedOrigin("*");//允许任何域名使用，2.4版本不加，加了会报错
        corsConfiguration.addAllowedHeader("*");//允许任何头
        corsConfiguration.addAllowedMethod("*");//允许任何方法
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());// 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
